package com.sphd.restaurantsystem.model;


import com.android.volley.VolleyError;
import com.sphd.restaurantsystem.info.InvestorInfo;
import com.sphd.restaurantsystem.info.InvestorItemInfo;
import com.sphd.restaurantsystem.interfaces.VolleyJsonObjectCallBack;
import com.sphd.restaurantsystem.presenter.AccountDetailPresenter;
import com.wzh.frame.utils.JsonUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Hu on 2016/11/03
 */

public class AccountDetailModelImpl implements AccountDetailModel, VolleyJsonObjectCallBack {
    AccountDetailPresenter accountDetailPresenter;

    @Override
    public void sendUrl(String url, AccountDetailPresenter accountDetailPresenter) {
        this.accountDetailPresenter = accountDetailPresenter;
        volleyUtil.setJsonObjectRequest(url, this);
    }

    @Override
    public void onResponse(JSONObject response) {
        try {
            double all_interest = response.getDouble("all_interest");
            List<InvestorItemInfo> investorItemInfos = new ArrayList<>();
            JSONArray jsonArray = response.getJSONArray("listyear");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject object = jsonArray.getJSONObject(i);
                InvestorItemInfo itemInfo = new InvestorItemInfo();
                if (object.has("sum")) {
                    itemInfo.setmYearTurnover(object.getDouble("sum"));
                }
                if (object.has("SUM(account_interest)")) {
                    itemInfo.setmYearCut(object.getDouble("SUM(account_interest)"));
                }
                if (object.has("date_format(account_day, '%Y')")) {
                    itemInfo.setmYear(object.getString("date_format(account_day, '%Y')"));

                }
                investorItemInfos.add(itemInfo);
            }
            List<InvestorInfo> investorInfoList = JsonUtil.getListFromString(response.getString("list"), InvestorInfo.class);
            accountDetailPresenter.sendRes(all_interest,investorItemInfos,investorInfoList);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onErrorResponse(VolleyError error) {
        accountDetailPresenter.sendError(error);
    }
}